package cn.yunbamboos.mybatis.mapping.methods.delete;

import cn.yunbamboos.mybatis.mapping.methods.BaseMethod;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;

public class DeleteByPrimaryKey extends BaseMethod {

    public DeleteByPrimaryKey(Configuration configuration, TableInfo tableInfo) {
        super("deleteByPrimaryKey", configuration, tableInfo, SqlCommandType.INSERT);
    }

    public DeleteByPrimaryKey(String methodName, Configuration configuration, TableInfo tableInfo) {
        super(methodName, configuration, tableInfo, SqlCommandType.INSERT);
    }

    @Override
    protected SqlSource getSqlSource() {
        String tableName = BACKTICK + this.tableInfo.getTableName() + BACKTICK;
        List<String> wheres = new ArrayList<>();

        this.tableInfo.getPrimaryKeyList().forEach(pk -> {
            String builder = BACKTICK + pk.getColumn() + BACKTICK +
                    SPACE + EQUALS + SPACE +
                    HASH_LEFT_BRACE + pk.getColumn() + RIGHT_BRACE;
            wheres.add(builder);
        });

        String sql = DELETE(tableName, wheres);

        return new RawSqlSource(configuration, sql, this.tableInfo.getEntityType());
    }

}
